
import {
    doPaste,
    copy,
} from './selection';
import {
    luckysheetsizeauto
} from '../view/resize';
import {
    selectHightlightShow
} from '../view/select';
import {
    luckysheetupdateCell,
} from '../view/updateCell';
import {
    luckysheetscrollevent
} from '../view/scroll';
import {
    highlightOneCell,
} from '../view/chooseOneCell';
import {
    clearmenuelement,
} from '../view/cleargridelement';
import {
    mergeborder,
} from '../model/mergeborder';
import {
    getMouseClickedPos,
} from '../utils/location';
import {
    showrightclickmenu,
} from '../utils/util';
import {
    luckysheet_searcharray
} from '../utils/sheetSearch';
import Store from '../store';

export {
    luckysheetHandler
};


function luckysheetHandler() {

    //When mouse up on the document - not hold left button of mouse cancel choose area
    $(document).on("mouseup.luckysheetEvent", function (event) {
        Store.luckysheet_select_status = false;
        window.cancelAnimationFrame(Store.jfautoscrollTimeout);
    })

    // When mouse move on the document - hold left button of mouse and choose the cell area
    $(document).on("mousemove.luckysheetEvent", function (event) {
        window.cancelAnimationFrame(Store.jfautoscrollTimeout);
        if (!!Store.luckysheet_rows_selected_status || !!Store.luckysheet_cols_selected_status || !!Store.luckysheet_select_status) {
            function mouseRender() {
                if(Store.luckysheet_select_status) {
                    //TODO：Let user config whether cell area can be selected
                    let mouseClickPos = getMouseClickedPos(event);
                    let row = mouseClickPos[0][1],
                        row_pre = mouseClickPos[0][0],
                        row_index = mouseClickPos[0][2];
                    let col = mouseClickPos[1][1],
                        col_pre = mouseClickPos[1][0],
                        col_index = mouseClickPos[1][2];
    
                    let last = $.extend(true, {}, Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1]);
    
                    let top = 0,
                        height = 0,
                        rowseleted = [];
                    if (last.top > row_pre) {
                        top = row_pre;
                        height = last.top + last.height - row_pre;
                        if (last.row[1] > last.row_focus) {
                            last.row[1] = last.row_focus;
                        }
                        rowseleted = [row_index, last.row[1]];
                    } else if (last.top == row_pre) {
                        top = row_pre;
                        height = last.top + last.height - row_pre;
                        rowseleted = [row_index, last.row[0]];
                    } else {
                        top = last.top;
                        height = row - last.top - 1;
                        if (last.row[0] < last.row_focus) {
                            last.row[0] = last.row_focus;
                        }
                        rowseleted = [last.row[0], row_index];
                    }
    
                    let left = 0,
                        width = 0,
                        columnseleted = [];
                    if (last.left > col_pre) {
                        left = col_pre;
                        width = last.left + last.width - col_pre;
                        if (last.column[1] > last.column_focus) {
                            last.column[1] = last.column_focus;
                        }
                        columnseleted = [col_index, last.column[1]];
                    } else if (last.left == col_pre) {
                        left = col_pre;
                        width = last.left + last.width - col_pre;
                        columnseleted = [col_index, last.column[0]];
                    } else {
                        left = last.left;
                        width = col - last.left - 1;
                        if (last.column[0] < last.column_focus) {
                            last.column[0] = last.column_focus;
                        }
                        columnseleted = [last.column[0], col_index];
                    }
    
                    let changeparam = mergeMoveMain(columnseleted, rowseleted, last, top, height, left, width);
                    if (changeparam != null) {
                        columnseleted = changeparam[0];
                        rowseleted = changeparam[1];
                        top = changeparam[2];
                        height = changeparam[3];
                        left = changeparam[4];
                        width = changeparam[5];
                    //    console.log(changeparam);
                    }
    
                    last["row"] = rowseleted;
                    last["column"] = columnseleted;
                    last["left_move"] = left;
                    last["width_move"] = width;
                    last["top_move"] = top;
                    last["height_move"] = height;
    
                    Store.luckysheet_select_save[Store.luckysheet_select_save.length - 1] = last;
                    selectHightlightShow();

                }
            }
            Store.jfautoscrollTimeout = window.requestAnimationFrame(mouseRender);
        }

    })

    // Click mouse left button - 1. active the cell ; 2. hold left button of mouse and ready for cell area choosen
    $("#luckysheet-cell-main, #luckysheetTableContent").mousedown(function (event) {

        if (event.which == "3") { // This return is for right click button copy cell area
            return;
        }
        
        highlightOneCell(event);
        clearmenuelement();

    }).dblclick(function (event) { // enter cell edit mode
        let mouseClickPos = getMouseClickedPos(event);
        let row_index = mouseClickPos[0][2],
            col_index = mouseClickPos[1][2];
        luckysheetupdateCell(row_index, col_index, Store.flowdata);
    }).mouseup(function (event) { // click right button of mouse for menu
        if (event.which == "3") { // right click open rightclick-menu
            clearmenuelement();
            highlightOneCell(event);
            let x = event.pageX;
            let y = event.pageY;
            showrightclickmenu($("#luckysheet-rightclick-menu"), x, y);
        }
    });

    $("#luckysheet-copy-btn, #luckysheet-cols-copy-btn, #luckysheet-paste-btn-title").click(function (event) {
        copy(event);
        $(this).parent().hide();
    });

    $("#luckysheet-copy-paste, #luckysheet-cols-paste-btn, #luckysheet-paste-btn-title").click(function (event) {
        alert("use ctrl+v for paste");
        $(this).parent().hide();
    });


    // Scroll mouse middle button , refresh cell main.
    $("#luckysheet-grid-window-1").mousewheel(function (event) {
        let scrollTop = $("#luckysheet-scrollbar-y").scrollTop();
        let visibledatarow_c = Store.visibledatarow;

        let row_st = luckysheet_searcharray(visibledatarow_c, scrollTop);

        let rowscroll = 0;

        let scrollNum = event.deltaFactor < 40 ? 1 : (event.deltaFactor < 80 ? 2 : 3);
        //一次滚动三行或三列
        if (event.deltaY != 0) {
            let row_ed, step = Math.round(scrollNum / Store.zoomRatio);
            step = step < 1 ? 1 : step;
            if (event.deltaY < 0) {
                row_ed = row_st + step;
                if (row_ed >= visibledatarow_c.length) {
                    row_ed = visibledatarow_c.length - 1;
                }
            } else {
                row_ed = row_st - step;

                if (row_ed < 0) {
                    row_ed = 0;
                }
            }
            rowscroll = row_ed == 0 ? 0 : visibledatarow_c[row_ed - 1];
            $("#luckysheet-scrollbar-y").scrollTop(rowscroll);
        }

    });

    // push scrollbar-x event
    $("#luckysheet-scrollbar-x").scroll(function () {
        luckysheetscrollevent();
    }).mousewheel(function (event, delta) {
        event.preventDefault();
    });

    // push scrollbar-y event
    $("#luckysheet-scrollbar-y").scroll(function () {
        luckysheetscrollevent();
    }).mousewheel(function (event, delta) {
        event.preventDefault();
    });

    // If brower's windows size change, refresh page
    $(window).resize(function () {
        let luckysheetDocument = document.getElementById(Store.container);
        if (luckysheetDocument) {
            luckysheetsizeauto();
        }
    });

    // paste from excel - operation system's ctrl+v for paste
    $(document).on("paste.luckysheetEvent", function (e) {
        doPaste(e);

    });

    //Disable browser's right click of mouse 禁止浏览器 右键默认菜单
    $(".luckysheet-grid-container, #luckysheet-rightclick-menu").on("contextmenu", function (e) {
        e.preventDefault();
    });
}


function mergeMoveMain(columnseleted, rowseleted, s, top , height, left , width){

    let mergeMoveData= {};
    let mergesetting = getSheetMerge();
    
    if(mergesetting == null){
        return;
    }

    let mcset = [];
    for(let key in mergesetting){
        mcset.push(key);
    }

    if(rowseleted[0] > rowseleted[1]){
        rowseleted[1] = rowseleted[0];
    }

    if(columnseleted[0] > columnseleted[1]){
        columnseleted[1] = columnseleted[0];
    }

    let offloop = true;
    mergeMoveData = {};

    while (offloop) {
        offloop = false;

        for(let i = 0; i < mcset.length; i++){
            let key = mcset[i];
            let mc = mergesetting[key];

            if(key in mergeMoveData){
                continue;
            }

            let changeparam  = mergeMove(mc, columnseleted, rowseleted, s, top, height, left, width);

            if(changeparam != null){
                mergeMoveData[key] = mc;
                
                columnseleted = changeparam[0];
                rowseleted= changeparam[1];
                top = changeparam[2];
                height = changeparam[3];
                left = changeparam[4];
                width = changeparam[5];

                offloop = true;
            }
            else{
                delete mergeMoveData[key];
            }
        }
    }
    
    return [columnseleted, rowseleted, top, height, left, width];
}

function mergeMove(mc, columnseleted, rowseleted, s, top , height, left , width){
    
    let row_st = mc.r, row_ed = mc.r + mc.rs - 1;
    let col_st = mc.c, col_ed = mc.c + mc.cs - 1;
    let ismatch = false;

    if(columnseleted[1] < columnseleted[0]){
        columnseleted[0] = columnseleted[1];
    }

    if(rowseleted[1] < rowseleted[0]){
        rowseleted[0] = rowseleted[1];
    }

    if( (columnseleted[0] <= col_st && columnseleted[1] >= col_ed && rowseleted[0] <= row_st && rowseleted[1] >= row_ed) || (!(columnseleted[1] < col_st || columnseleted[0] > col_ed) && !(rowseleted[1] < row_st || rowseleted[0] > row_ed))){
        let margeset = mergeborder(Store.flowdata, mc.r, mc.c);
        if(!!margeset){
            let row = margeset.row[1],
                row_pre = margeset.row[0],
                row_index = margeset.row[2],
                col = margeset.column[1],
                col_pre = margeset.column[0],
                col_index = margeset.column[2];

            if(!(columnseleted[1] < col_st || columnseleted[0] > col_ed)){
                //向上滑动
                if(rowseleted[0] <= row_ed && rowseleted[0] >= row_st){
                    height += top - row_pre;
                    top = row_pre;
                    rowseleted[0] = row_st;
                }
                
                //向下滑动或者居中时往上滑动的向下补齐
                if(rowseleted[1] >= row_st && rowseleted[1] <= row_ed){
                    if(s.row_focus >= row_st && s.row_focus <= row_ed){
                        height = row - top;
                    }
                    else{
                        height = row - top;
                    }
                    
                    rowseleted[1] = row_ed;
                }
            }
            
            if(!(rowseleted[1] < row_st || rowseleted[0] > row_ed)){
                if(columnseleted[0] <= col_ed && columnseleted[0] >= col_st){
                    width += left - col_pre;
                    left = col_pre;
                    columnseleted[0] = col_st;
                }
                
                //向右滑动或者居中时往左滑动的向下补齐
                if(columnseleted[1] >= col_st && columnseleted[1] <= col_ed){
                    if(s.column_focus >= col_st && s.column_focus <= col_ed){
                        width = col - left;
                    }
                    else{
                        width = col - left;
                    }
                    
                    columnseleted[1] = col_ed;
                }
            }

            ismatch = true;
        }
    }
   
    if(ismatch){
        return [columnseleted, rowseleted, top , height, left , width];
    }
    else{
        return null;
    }
}

function getSheetMerge() {
    if(Store.config.merge == null){
        return null;
    }

    return Store.config.merge;
}


